package com.twu.biblioteca;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: kush jain
 * Date: 7/4/13
 * Time: 9:29 AM
 * To change this template use File | Settings | File Templates.
 */
public class LibraryManager {
    private InventoryManager invMgr;
    private TransactionManagaer transactionMgr;
    private UserManager userMgr;
    LibraryManager()
    {
        invMgr=new InventoryManager();
        transactionMgr = new TransactionManagaer();
        userMgr = new UserManager();
        load(Constants.dataStorage);

    }
    public InventoryManager searchBookByTitle()
    {

        String Title = Presenter.getInput("Enter the title of the book you are looking for:");
        InventoryManager searchResult = invMgr.getInventoryOfBooksContainingTitle(Title);
        if(searchResult.getNoOfBooks()==0)  {
            Presenter.Say("Sorry we don't have that book yet");
            return searchResult;
        }
        Presenter.Say("Search Results");
        Presenter.Say(searchResult.getStringOfBooksList());
        Presenter.Say("Displaying " + searchResult.getNoOfBooks() + " Results") ;
        return searchResult;
    }
    public void addNewBook()
    {
        String title = Presenter.getInput("Enter the title of the book: ");
        String author= Presenter.getInput("Enter the author's name of the book: ");
        Presenter.Say(invMgr.addNewBook(title,author));

    }
    public void addNewUser()
    {
        User newUser = new User();
        newUser.read();
        Presenter.Say(userMgr.addUser(newUser));
    }
    public void addNewMovie()
    {
        String movieName = Presenter.getInput("Enter the name of the Movie: ");
        int year = Integer.parseInt(Presenter.getInput("Enter the year in which the Movie was released:"));
        String director= Presenter.getInput("Enter the name of the director: ");
        if (Presenter.getInput("Do you have the rating? (yes/no)").equals("no")){
            Presenter.Say(invMgr.addNewMovie(movieName,year,director));
            return;
        }
        int rating= Integer.parseInt(Presenter.getInput("Enter the rating on a scale of 1 to 10: "));
        Presenter.Say(invMgr.addNewMovie(movieName, year, director, rating));
    }
    public void checkMemberShipStatus()
    {
       if(Session.curuser==null)
           Presenter.Say("Please talk to a Librarian. Thank you.");
       else
           Presenter.Say(Session.curuser.print());

    }
    public void removeBook(){

        InventoryManager searchResult = searchBookByTitle();
        if(searchResult.getNoOfBooks()==1) {
            Presenter.Say(invMgr.removeBook(searchResult.getBookAtIndex(0).getBookId()));
            return;
        }
        Presenter.Say(invMgr.removeBook(Integer.parseInt(Presenter.getInput("Enter Book ID of the book you wish to delete:"))));

    }
    public void removeUser(){

        Presenter.Say(userMgr.removeUser(Presenter.getInput("Enter usernaem of the user you wish to delete:")));

    }
    public void reserveBook(int bookID){

        if(transactionMgr.isReserved(bookID)) {
            Presenter.Say("The book is already reserved");
            return;
        }
        transactionMgr.addReservationTransaction(bookID);
        Presenter.Say("Thank You! Enjoy the book");
    }

    public void reserveBook(){

        InventoryManager searchResult = searchBookByTitle();
        if(searchResult.getNoOfBooks()==0)
                return;
        if(searchResult.getNoOfBooks()==1) {
                reserveBook(searchResult.getBookAtIndex(0).getBookId());
                return;
        }
        int userBookId =  Integer.parseInt(Presenter.getInput("Can you please specify the bookID of the book you wish to reserve"));
        if(invMgr.getBookByBookID(userBookId)==null) {
            Presenter.Say("The book does not exist");
            return;
        }
        reserveBook(userBookId);

    }

    public void freeBook(){

        InventoryManager searchResult = searchBookByTitle();
        if(searchResult.getNoOfBooks()==1) {
            transactionMgr.freeBook(searchResult.getBookAtIndex(0).getBookId(), invMgr);
            return;
        }
        int userBookId =  Integer.parseInt(Presenter.getInput("Enter the bookID of the book you wish to free from its reserved status"));
        transactionMgr.freeBook(userBookId, invMgr);
    }
    public void showReservedBooks()
    {
        Presenter.Say(transactionMgr.getReservedBooks(invMgr).getStringOfBooksList());
        Presenter.Say("Total: " + transactionMgr.getReservedBooks(invMgr).getNoOfBooks() + " Books") ;

    }
    public void loginAsAdmin()
    {
        String Password = Presenter.getInput("Enter Admin Password");
        if(Password.equals(Constants.ADMIN_PASSWORD))
        {
            Session.isAdmin=true;
            Session.curuser=null;
            Presenter.Say("Welcome Administrator");
            return;
        }
        Presenter.Say("Invalid Password");

    }
    public void loginAsMember()
    {
        String username = Presenter.getInput("Enter Username (Library Card Number):");
        String password = Presenter.getInput("Enter Password:");
        if(userMgr.authenticate(username,password))
        {
            Session.curuser=userMgr.getUser(username);
            Presenter.Say("Welcome " + Session.curuser.getName());
            return;
        }
        Presenter.Say("Invalid Username or Password");

    }
    public void showAllMovies()
    {
        Presenter.Say(String.format("%-30s\t%4s\t%-30s\t%-10s","Movie Name","Year","Director","Rating"));
        Presenter.Say(invMgr.getStringOfMoviesList());
        Presenter.Say("Total: " + invMgr.getNoOfMovies() + " Movies");
        Presenter.Say("Press Enter to continue");
        Presenter.waitForEnterKey();
    }
    public void showAllBooks()
    {
        Presenter.Say(invMgr.getStringOfBooksList());
        Presenter.Say("Total: " + invMgr.getNoOfBooks() + " Books");
        Presenter.Say("Press Enter to continue");
        Presenter.waitForEnterKey();
    }
    public void logout()
    {
        Session.curuser=null;
        Session.isAdmin=false;
        Presenter.Say("You have successfully Logged Out");
    }
    public void serviceUserChoice(String choice)
    {
           if(choice.equals("Add Book"))
                addNewBook();
           if(choice.equals("Logout"))
                logout();
           if(choice.equals("Add User"))
                addNewUser();
           if(choice.equals("Remove User"))
                removeUser();
           if(choice.equals("Remove Book"))
                removeBook();
           if(choice.equals("Show All Books"))
              showAllBooks();
           if(choice.equals("Search Book by Title"))
               searchBookByTitle();
           if(choice.equals("Check Membership Status"))
               checkMemberShipStatus();
           if(choice.equals("Reserve Book"))
                reserveBook();
           if(choice.equals("Free Reserved Book"))
                freeBook();
           if(choice.equals("Show Reserved Books"))
               showReservedBooks();
           if(choice.equals("Login as Administrator"))
               loginAsAdmin();
           if(choice.equals("Login as Member"))
               loginAsMember();
           if(choice.equals("Show List of Movies"))
               showAllMovies();
           if(choice.equals("Add Movie"))
               addNewMovie();
    }

    public void save(String fileName)
    {

        try{
            FileOutputStream saveFile=new FileOutputStream(fileName);
            ObjectOutputStream objOutputStream = new ObjectOutputStream(saveFile);
            objOutputStream.writeObject(invMgr);
            objOutputStream.writeObject(userMgr);
            objOutputStream.writeObject(transactionMgr);
            objOutputStream.close();
        }
        catch(Exception e){

        }

    }
    public void load(String fileName)
    {

        try{
            FileInputStream loadFile = new FileInputStream(fileName);
            ObjectInputStream objInputStream = new ObjectInputStream(loadFile);
            invMgr = (InventoryManager) objInputStream.readObject();
            userMgr = (UserManager) objInputStream.readObject();
            transactionMgr = (TransactionManagaer)objInputStream.readObject();
            objInputStream.close();

        }
        catch(Exception e){

        }
    }

}
